package aes

import (
	"crypto/aes"
	cipher2 "crypto/cipher"
	"crypto/rand"
	"encoding/hex"
	"io"
)

var key = []byte("-sfd23@%$#sdfgdfg345^%$-9832sd12")

func Encrypter(src string) string {
	plaintext := []byte(src)

	block, err := aes.NewCipher(key)
	if err != nil {
		panic(err)
	}

	// The IV needs to be unique,but not secure.Therefore it's common to
	// include it at the beginning of the cipherText
	cipherText := make([]byte, aes.BlockSize+len(plaintext))
	iv := cipherText[:aes.BlockSize]
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		panic(err)
	}

	stream := cipher2.NewCFBEncrypter(block, iv)
	stream.XORKeyStream(cipherText[aes.BlockSize:], plaintext)

	// It's important to remember that cipherText must be authenticated
	//(i.e. by using crypto/hmac) as well as being encrypted in order to
	//be secure.
	return hex.EncodeToString(cipherText)

}

func Decrypter(src string) string {
	cipherText, _ := hex.DecodeString(src)

	block, err := aes.NewCipher(key)
	if err != nil {
		panic(err)
	}

	// The IV needs to be unique,but not secure.Therefore it's common to
	// include it at the beginning of the cipherText
	if len(cipherText) < aes.BlockSize {
		panic(" cipherText too short!")
	}

	iv := cipherText[:aes.BlockSize]
	cipherText = cipherText[aes.BlockSize:]

	stream := cipher2.NewCFBDecrypter(block, iv)

	// XORKeyStream can work in-place if the two arguments are the same
	stream.XORKeyStream(cipherText, cipherText)
	return string(cipherText)
}
